 	/**
 * @author {CaoGuangHui}
 */
$.extend($.fn.tabs.methods, {
    /**
     * tabs组件每个tab panel对应的小工具条绑定的事件没有传递事件参数
     * 本函数修正这个问题
     * @param {[type]} jq [description]
     */
    addEventParam: function(jq) {
        return jq.each(function() {
            var that = this;
            var headers = $(this).find('>div.tabs-header>div.tabs-wrap>ul.tabs>li');
            headers.each(function(i) {
                var tools = $(that).tabs('getTab', i).panel('options').tools;
                if (typeof tools != "string") {
                    $(this).find('>span.tabs-p-tool a').each(function(j) {
                        $(this).unbind('click').bind("click", {
                            handler: tools[j].handler
                        }, function(e) {
                            if ($(this).parents("li").hasClass("tabs-disabled")) {
                                return;
                            }
                            e.data.handler.call(this, e);
                        });
                    });
                }
            })
        });
    },
    /**
     * 加载iframe内容
     * @param  {jq Object} jq     [description]
     * @param  {Object} params    params.which:tab的标题或者index;params.iframe:iframe的相关参数
     * @return {jq Object}        [description]
     */
    loadTabIframe:function(jq,params){
        return jq.each(function(){
            var taboptions = $(this).tabs("options");
            var $tab = $(this).tabs('getTab',params.which);
            if($tab==null) return;

            var $tabBody = $tab.panel('body');

            //销毁已有的iframe
            var $frame=$('iframe', $tabBody);
            if($frame.length>0){
                try{//跨域会拒绝访问，这里处理掉该异常
                    $frame[0].contentWindow.document.write('');
                    $frame[0].contentWindow.close();
                }catch(e){
                    //Do nothing
                }
                $frame.remove();
                if($.browser.msie){
                    CollectGarbage();
                }
            }
            $tabBody.html('');

            $tabBody.css({'overflow':'hidden','position':'relative'});
            var $mask = $('<div style="position:absolute;width:100%;height:100%;background:#ccc;z-index:1000;opacity:0.3;filter:alpha(opacity=30);"><div>').appendTo($tabBody);
            var $maskMessage = $('<div class="mask-message" style="border-radius: 10px;z-index:3;width:auto;height:16px;line-height:16px;position:absolute;top:50%;left:50%;margin-top:-20px;margin-left:-92px;border:2px solid #d4d4d4;padding: 12px 5px 10px 30px;background: #ffffff url(\''+app.approot+'themes/'+app.theme+'/images/loading16x16.gif\') no-repeat scroll 5px center;">' + (params.iframe.message || '加载页面...') + '</div>').appendTo($tabBody);
            var $containterMask = $('<div style="position:absolute;width:100%;height:100%;z-index:1;background:#fff;"></div>').appendTo($tabBody);
            var $containter = $('<div style="position:absolute;width:100%;height:100%;z-index:0;"></div>').appendTo($tabBody);

            var iframe = document.createElement("iframe");
            var src = params.src || params.iframe.src;
            if(src && src.indexOf("?")>0){
                iframe.src = src + "&_rt="+Math.random();
            }else{
                iframe.src = src + "?_rt="+Math.random();
            }
            iframe.frameBorder = params.iframe.frameBorder || 0;
            iframe.height = params.iframe.height || '100%';
            iframe.width = params.iframe.width || '100%';
            if (iframe.attachEvent){
                iframe.attachEvent("onload", function(){
                    params.op.iwin = iframe.contentWindow;
                    taboptions.iwin = iframe.contentWindow;
                    if(iframe.contentWindow && iframe.contentWindow.app){
                        iframe.contentWindow.app.opener = window;
                        iframe.contentWindow.app.currentTabid = params.op.id;
                    }
                    $([$mask[0],$maskMessage[0]]).fadeOut(params.iframe.delay || 'slow',function(){
                        $(this).remove();
                        if($(this).hasClass('mask-message')){
                            $containterMask.fadeOut(params.iframe.delay || 'slow',function(){
                                $(this).remove();
                            });
                        }
                    });
                    if(params.op.onload)params.op.onload(iframe.contentWindow);
                });
            } else {
                iframe.onload = function(){
                    params.op.iwin = iframe.contentWindow;
                    taboptions.iwin = iframe.contentWindow;
                    try
                    {
	                    if(iframe.contentWindow && iframe.contentWindow.app){
	                        iframe.contentWindow.app.opener = window;
	                        iframe.contentWindow.app.currentTabid = params.op.id;
	                    }
                    }
                    catch (ex){}
                    $([$mask[0],$maskMessage[0]]).fadeOut(params.iframe.delay || 'slow',function(){
                        $(this).remove();
                        if($(this).hasClass('mask-message')){
                            $containterMask.fadeOut(params.iframe.delay || 'slow',function(){
                                $(this).remove();
                            });
                        }
                    });
                    if(params.op.onload)params.op.onload(iframe.contentWindow);
                };
            }
            $containter[0].appendChild(iframe);
            if(typeof(params.op.mask) != "undefined" && !params.op.mask){$mask.remove();}
        });
    },
    /**
     * 增加iframe模式的标签页
     * @param {[type]} jq     [description]
     * @param {[type]} params [description]
     */
    addIframeTab:function(jq,params){
        return jq.each(function(){
            if(params.tab && params.tab.href){
                delete params.tab.href;
            }
            $(this).tabs('add',params.tab || params);
            
            $(this).tabs('loadTabIframe',{'which':$(this).tabs("tabs").length-1,'iframe':params.iframe || params,op:params});
        });
    },
    /**
     * 更新tab的iframe内容
     * @param  {jq Object} jq     [description]
     * @param  {Object} params [description]
     * @return {jq Object}        [description]
     */
    updateIframeTab:function(jq,params){
        return jq.each(function(){
            params.iframe = params.iframe || {};
            if(!params.iframe.src){
                var $tab = $(this).tabs('getTab',params.which);
                if($tab==null) return;
                var $tabBody = $tab.panel('body');
                var $iframe = $tabBody.find('iframe');
                if($iframe.length===0) return;
                $.extend(params.iframe,{'src':$iframe.attr('src')});
            }
            $(this).tabs('loadTabIframe',params);
        });
    }
});

/**
 * 解决在隐藏状态下刷新iframe内的内容导致界面内容高度不可见
 * 打开标签页之后触发iframe内界面区域大小变化事件
 */
$.extend($.fn.tabs.defaults,{
    onSelect : function(title,index){
        var ctab = $(this).tabs("getTab",index);
        var iframe = $("iframe",ctab);
        if(iframe.length >0 && iframe[0].contentWindow && iframe[0].contentWindow.$){
            //setTimeout(function(){
                var panel = iframe[0].contentWindow.$(".easyui-panel");
                if(panel.length>0){
                    panel.panel("doLayout");
                }
            //},50);
            /*
            var iwin = iframe[0].contentWindow;
            $(iwin).trigger('resize');
            */
        }
    }
});

/**
 * 解决datagrid 单元格显示html编码问题
 */
$.extend($.fn.datagrid.defaults.view,{
    render: function(target, container, frozen){
        var state = $.data(target, 'datagrid');
        var opts = state.options;
        var rows = state.data.rows;
        var fields = $(target).datagrid('getColumnFields', frozen);

        if (frozen){
            if (!(opts.rownumbers || (opts.frozenColumns && opts.frozenColumns.length))){
                return;
            }
        }

        var table = ['<table class="datagrid-btable" cellspacing="0" cellpadding="0" border="0"><tbody class="datagrid-databody">'];

        table.push('</tbody></table>');
        $(container).html(table.join(''));
        var bd = $(".datagrid-databody",container);


        for(var i=0; i<rows.length; i++) {
            // get the class and style attributes for this row
            var cls = (i % 2 && opts.striped) ? 'class="datagrid-row datagrid-row-alt"' : 'class="datagrid-row"';
            var styleValue = opts.rowStyler ? opts.rowStyler.call(target, i, rows[i]) : '';
            var style = styleValue ? 'style="' + styleValue + '"' : '';
            var rowId = state.rowIdPrefix + '-' + (frozen?1:2) + '-' + i;
            var tr =$('<tr id="' + rowId + '" datagrid-row-index="' + i + '" ' + cls + ' ' + style + '></tr>');
            bd.append(tr);
            //tr.append($(this._renderRow.call(this, target, fields, frozen, i, rows[i],tr)));
            this._renderRow.call(this, target, fields, frozen, i, rows[i],tr);
        }

        //$(target).datagrid("loading");

    },
    _renderRow: function(target, fields, frozen, rowIndex, rowData,tr){
        var opts = $.data(target, 'datagrid').options;
        //var tr = $();
        //ptr.append(tr);
        if (frozen && opts.rownumbers){
            var rownumber = rowIndex + 1;
            if (opts.pagination){
                rownumber += ((opts.pageNumber<=0?1:opts.pageNumber) - 1) * opts.pageSize;
            }
            tr.append('<td class="datagrid-td-rownumber"><div class="datagrid-cell-rownumber">'+rownumber+'</div></td>');
        }
        for(var i=0; i<fields.length; i++){
            var field = fields[i];
            var col = $(target).datagrid('getColumnOption', field);
            if (col){
                var value = rowData[field];	// the field value
                // get the cell style attribute
                var styleValue = col.styler ? (col.styler(value, rowData, rowIndex)||'') : '';
                var style = col.hidden ? 'style="display:none;' + styleValue + '"' : (styleValue ? 'style="' + styleValue + '"' : '');
                var cc = [];
                cc.push('<td field="' + field + '" ' + style + '>');

                if (col.checkbox){
                    var style = '';
                } else {
                    var style = '';
//											style += 'text-align:' + (col.align || 'left') + ';';
                    if (col.align){style += 'text-align:' + col.align + ';'}
                    if (!opts.nowrap){
                        style += 'white-space:normal;height:auto;';
                    } else if (opts.autoRowHeight){
                        style += 'height:auto;';
                    }
                }

                cc.push('<div style="' + style + '" ');
                if (col.checkbox){
                    cc.push('class="datagrid-cell-check ');
                } else {
                    cc.push('class="datagrid-cell ' + col.cellClass);
                }
                cc.push('">');
                cc.push('</div>');
                cc.push('</td>');
                var td = $(cc.join(''));
                var div = $("div",td);
                tr.append(td);
                if (col.checkbox){
                    div.append('<input type="checkbox" name="' + field + '" value="' + (value!=undefined ? value : '') + '"/>');
                } else if (col.formatter){
                    var fm = col.formatter(value, rowData, rowIndex,div);
                    if(fm != null)div.append(fm);
                } else if(value != null){
                    div.text(value);
                    div.prop("title",value);
                }
            }
        }
        return  tr;
    },updateRow: function(target, rowIndex, row){
        var opts = $.data(target, 'datagrid').options;
        var rows = $(target).datagrid('getRows');
        $.extend(rows[rowIndex], row);
        var styleValue = opts.rowStyler ? opts.rowStyler.call(target, rowIndex, rows[rowIndex]) : '';

        function _update(frozen){
            var fields = $(target).datagrid('getColumnFields', frozen);
            var tr = opts.finder.getTr(target, rowIndex, 'body', (frozen?1:2));
            var checked = tr.find('div.datagrid-cell-check input[type=checkbox]').is(':checked');
            tr.empty();
            //tr.append(this._renderRow.call(this, target, fields, frozen, rowIndex, rows[rowIndex]));
            this._renderRow.call(this, target, fields, frozen, rowIndex, rows[rowIndex],tr);
            tr.attr('style', styleValue || '');
            if (checked){
                tr.find('div.datagrid-cell-check input[type=checkbox]')._propAttr('checked', true);
            }
        }

        _update.call(this, true);
        _update.call(this, false);
        $(target).datagrid('fixRowHeight', rowIndex);
    }
});

/**
 * 解决treegrid 单元格显示html编码问题
 */
$.extend($.fn.treegrid.defaults.view, {
    /*renderRow: function (_8a1, _8a2, _8a3, _8a4, row) {
        var opts = $.data(_8a1, "treegrid").options;
        var cc = [];
        if (_8a3 && opts.rownumbers) {
            cc.push("<td class=\"datagrid-td-rownumber\"><div class=\"datagrid-cell-rownumber\">0</div></td>");
        }
        for (var i = 0; i < _8a2.length; i++) {
            var _8a5 = _8a2[i];
            var col = $(_8a1).datagrid("getColumnOption", _8a5);
            if (col) {
                var css = col.styler ? (col.styler(row[_8a5], row) || "") : "";
                var _8a6 = "";
                var _8a7 = "";
                if (typeof css == "string") {
                    _8a7 = css;
                } else {
                    if (cc) {
                        _8a6 = css["class"] || "";
                        _8a7 = css["style"] || "";
                    }
                }
                var cls = _8a6 ? "class=\"" + _8a6 + "\"" : "";
                var _8a8 = col.hidden ? "style=\"display:none;" + _8a7 + "\"" : (_8a7 ? "style=\"" + _8a7 + "\"" : "");
                cc.push("<td field=\"" + _8a5 + "\" " + cls + " " + _8a8 + ">");
                var _8a8 = "";
                if (!col.checkbox) {
                    if (col.align) {
                        _8a8 += "text-align:" + col.align + ";";
                    }
                    if (!opts.nowrap) {
                        _8a8 += "white-space:normal;height:auto;";
                    } else {
                        if (opts.autoRowHeight) {
                            _8a8 += "height:auto;";
                        }
                    }
                }
                cc.push("<div style=\"" + _8a8 + "\" ");
                if (col.checkbox) {
                    cc.push("class=\"datagrid-cell-check ");
                } else {
                    cc.push("class=\"datagrid-cell " + col.cellClass);
                }
                cc.push("\">");
                if (col.checkbox) {
                    if (row.checked) {
                        cc.push("<input type=\"checkbox\" checked=\"checked\"");
                    } else {
                        cc.push("<input type=\"checkbox\"");
                    }
                    cc.push(" name=\"" + _8a5 + "\" value=\"" + (row[_8a5] != undefined ? row[_8a5] : "") + "\">");
                } else {
                    var val = null;
                    if (col.formatter) {
                        val = col.formatter(row[_8a5], row);
                    } else {
                        val = row[_8a5];
                        if(val != null)val = app.htmlEncode(val);
                    }
                    if (_8a5 == opts.treeField) {
                        for (var j = 0; j < _8a4; j++) {
                            cc.push("<span class=\"tree-indent\"></span>");
                        }
                        if (row.state == "closed") {
                            cc.push("<span class=\"tree-hit tree-collapsed\"></span>");
                            cc.push("<span class=\"tree-icon tree-folder " + (row.iconCls ? row.iconCls : "") + "\"></span>");
                        } else {
                            if (row.children && row.children.length) {
                                cc.push("<span class=\"tree-hit tree-expanded\"></span>");
                                cc.push("<span class=\"tree-icon tree-folder tree-folder-open " + (row.iconCls ? row.iconCls : "") + "\"></span>");
                            } else {
                                cc.push("<span class=\"tree-indent\"></span>");
                                cc.push("<span class=\"tree-icon tree-file " + (row.iconCls ? row.iconCls : "") + "\"></span>");
                            }
                        }
                        cc.push("<span class=\"tree-title\">" + val + "</span>");
                    } else {
                        cc.push(val);
                    }
                }
                cc.push("</div>");
                cc.push("</td>");
            }
        }
        return cc.join("");
    }*/
   /* renderRow:function(_993,_994,_995,_996,row){
var _997=$.data(_993,"treegrid");
var opts=_997.options;
var cc=[];
if(_995&&opts.rownumbers){
cc.push("<td class=\"datagrid-td-rownumber\"><div class=\"datagrid-cell-rownumber\">0</div></td>");
}
for(var i=0;i<_994.length;i++){
var _998=_994[i];
var col=$(_993).datagrid("getColumnOption",_998);
if(col){
var css=col.styler?(col.styler(row[_998],row)||""):"";
var cs=this.getStyleValue(css);
var cls=cs.c?"class=\""+cs.c+"\"":"";
var _999=col.hidden?"style=\"display:none;"+cs.s+"\"":(cs.s?"style=\""+cs.s+"\"":"");
cc.push("<td field=\""+_998+"\" "+cls+" "+_999+">");
var _999="";
if(!col.checkbox){
if(col.align){
_999+="text-align:"+col.align+";";
}
if(!opts.nowrap){
_999+="white-space:normal;height:auto;";
}else{
if(opts.autoRowHeight){
_999+="height:auto;";
}
}
}
cc.push("<div style=\""+_999+"\" ");
if(col.checkbox){
cc.push("class=\"datagrid-cell-check ");
}else{
cc.push("class=\"datagrid-cell "+col.cellClass);
}
cc.push("\">");
if(col.checkbox){
if(row.checked){
cc.push("<input type=\"checkbox\" checked=\"checked\"");
}else{
cc.push("<input type=\"checkbox\"");
}
cc.push(" name=\""+_998+"\" value=\""+(row[_998]!=undefined?row[_998]:"")+"\">");
}else{
var val=null;
if(col.formatter){
val=col.formatter(row[_998],row);
}else{
val=row[_998];
if(val != null && app && app.htmlEncode)val = app.htmlEncode(val);
}
if(_998==opts.treeField){
for(var j=0;j<_996;j++){
cc.push("<span class=\"tree-indent\"></span>");
}
if(row.state=="closed"){
cc.push("<span class=\"tree-hit tree-collapsed\"></span>");
cc.push("<span class=\"tree-icon tree-folder "+(row.iconCls?row.iconCls:"")+"\"></span>");
}else{
if(row.children&&row.children.length){
cc.push("<span class=\"tree-hit tree-expanded\"></span>");
cc.push("<span class=\"tree-icon tree-folder tree-folder-open "+(row.iconCls?row.iconCls:"")+"\"></span>");
}else{
cc.push("<span class=\"tree-indent\"></span>");
cc.push("<span class=\"tree-icon tree-file "+(row.iconCls?row.iconCls:"")+"\"></span>");
}
}
if(this.hasCheckbox(_993,row)){
var flag=0;
var crow=$.easyui.getArrayItem(_997.checkedRows,opts.idField,row[opts.idField]);
if(crow){
flag=crow.checkState=="checked"?1:2;
}else{
var prow=$.easyui.getArrayItem(_997.checkedRows,opts.idField,row._parentId);
if(prow&&prow.checkState=="checked"&&opts.cascadeCheck){
flag=1;
row.checked=true;
$.easyui.addArrayItem(_997.checkedRows,opts.idField,row);
}else{
if(row.checked){
$.easyui.addArrayItem(_997.tmpIds,row[opts.idField]);
}
}
row.checkState=flag?"checked":"unchecked";
}
cc.push("<span class=\"tree-checkbox tree-checkbox"+flag+"\"></span>");
}else{
row.checkState=undefined;
row.checked=undefined;
}
cc.push("<span class=\"tree-title\">"+val+"</span>");
}else{
cc.push(val);
}
}
cc.push("</div>");
cc.push("</td>");
}
}
return cc.join("");
}*/
});
/**
 * tree 显示html 问题
 * 扩展属性 isHtml ture:显示html,false:显示文本
 */
$.extend($.fn.tree.defaults, {formatter: function (node) {
    var op = $(this).tree("options");
    if(!op.isHtml)
    if(node.text != null) return app.htmlEncode(node.text);
    return node.text;
}});
/**
 * tree 显示html 问题
 * 扩展属性 isHtml ture:显示html,false:显示文本
 */
$.extend($.fn.combotree.defaults, {formatter: function (node) {
    var op = $(this).tree("options");
    if(!op.isHtml)
        if(node.text != null) return app.htmlEncode(node.text);
    return node.text;
}});

/**
 * datagrid 延迟加载
 * 参数initalized:false 可设置初始化不加载数据
 * 不配置此参数按照默认行为加载数据
 */
$.extend($.fn.datagrid.defaults, {
	loader:function(param, success, error) {
	    var that = $(this);
	    var opts = that.datagrid("options");
	    if (!opts.url) {
	        return false;
	    }
	    if (typeof(opts.initalized) == 'undefined' || opts.initalized) {
	        $.ajax({
	            type: opts.method,
	            url: opts.url,
	            data: param,
	            dataType: "json",
	            success: function (data) {
	                if(data){
	                	success(data);
	                }else{
	                	success([]);
	                }
	            },
	            error: function (data) {
	                error.apply(this, arguments);
	            }
	        });
	
	    }else{
	    	success([]);
	    }
	    opts.initalized = true;
	    return true;
	}
});

